const state = {
  token: localStorage.getItem('token') || null,
  user: JSON.parse(localStorage.getItem('user')) || null,
  // 模拟用户数据库
  users: JSON.parse(localStorage.getItem('users_db')) || [
    { account: 'admin', password: '123456' }
  ]
}

const mutations = {
  SET_TOKEN (state, token) {
    state.token = token
    localStorage.setItem('token', token)
  },
  SET_USER (state, user) {
    state.user = user
    localStorage.setItem('user', JSON.stringify(user))
  },
  ADD_USER (state, user) {
    state.users.push(user)
    localStorage.setItem('users_db', JSON.stringify(state.users))
  },
  CLEAR_AUTH (state) {
    state.token = null
    state.user = null
    localStorage.removeItem('token')
    localStorage.removeItem('user')
  }
}

const actions = {
  // 纯前端登录验证
  async login ({ commit, state }, credentials) {
    return new Promise((resolve, reject) => {
      setTimeout(() => { // 模拟异步
        const user = state.users.find(
          u => u.account === credentials.account &&
               u.password === credentials.password
        )

        if (user) {
          const fakeToken = `fake-jwt-${Math.random().toString(36).slice(2)}`
          const userData = { account: user.account }

          commit('SET_TOKEN', fakeToken)
          commit('SET_USER', userData)
          resolve({ token: fakeToken, user: userData })
        } else {
          reject(new Error('用户名或密码错误'))
        }
      }, 500) // 模拟网络延迟
    })
  },

  // 纯前端注册
  async register ({ commit, state }, userData) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        const exists = state.users.some(u => u.account === userData.account)

        if (exists) {
          reject(new Error('用户名已存在'))
        } else if (userData.password !== userData.confirmPassword) {
          reject(new Error('两次密码输入不一致'))
        } else {
          const newUser = {
            account: userData.account,
            password: userData.password
          }

          commit('ADD_USER', newUser)
          resolve({ success: true })
        }
      }, 500)
    })
  },

  logout ({ commit }) {
    commit('CLEAR_AUTH')
  }
}

const getters = {
  isAuthenticated: state => !!state.token,
  currentUser: state => state.user
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
